import { reactive, inject, provide, toRaw } from 'vue';
import { ConsoleLogger } from '@/utils/debug-log';
import { AnswersID, StuID, TeacherID, WorkID } from '../types';
import { ImgUrls, PlantHomeWork, SimplifyUrls, StdHomeWork } from '../types/jobs';
import { IImageState, ImageInfo, ImageType } from '../types/jobs/images';
import { ImageToolManage } from '../core/imageTool';
import { CurrentSubject, ESubmitType } from '../types/jobs/homeWork';
import { getCHNumber } from '@/utils/chString';

const console = new ConsoleLogger('图像hooks');

const useImageSymbol = Symbol('useImagestore');

export interface IUseImageStoreFn {
  (): IUseImageStore;
  __CurrentStore?: IUseImageStore;
}
/** 图像容器*/
export type ImageDomContain = { [key: string]: { r: HTMLDivElement; node: ImageInfo; id: AnswersID } };
/** 图像管理节点*/
export type ImageManageInfo = { idx: number; im: ImageToolManage; id: AnswersID };

export interface IImageHooksState {
  stuID: StuID;
  /**当前序号，轮播使用 */
  currentImageIndex: number;
  // activeImageManagesIdx: number;
  // activeAnswersId: AnswersID| null;
  imageDomContain: Partial<ImageDomContain>;
  activeImageManages: ImageManageInfo | null;
  imageManages: Array<ImageManageInfo>;
  /**是否编辑状态 */
  isEditor: boolean;
  /**是否修改 */
  hasCurrect: boolean;
  /**轮播原始图：修改图 */
  images: ImageType;
}

export interface IUseImageStore {
  state: IImageHooksState;
  getActiveImageManagesById: (id: AnswersID) => void;
  /** 设置获取图像顺序*/
  changeActiveImageManages: (idx: number, id: AnswersID) => void;
  /**获取批改图像状态 */
  getCorrectImageStatus: (list: Array<CurrentSubject>) => { text: string; status: boolean };
  /**激活当前批改的图片 */
  activateSubjectManages: () => void;
  /**初始化图像 */
  addImageTool: (dom: HTMLDivElement, node: ImageInfo, idx: number, id: AnswersID) => Promise<void>;
  /** 获得图片信息并初始化*/
  initImageUrl: (submitType: ESubmitType, currentStdHomeWork: StdHomeWork) => void;
}

/**
 *  * useImageStore 用户hooks.
 * @function
 * @params {stu_id} StuID - 用户信息.{domId} domId
 * @returns store extend useImageProvide
 */
export const useImageProvide: (stuID: StuID) => IUseImageStore = (stuID: StuID) => {
  console.log('初始化图像编辑');
  //判断学生id

  const state = reactive<IImageHooksState>({
    stuID: stuID,
    currentImageIndex: 1,
    activeImageManages: null,
    imageDomContain: {},
    imageManages: [],
    isEditor: false,
    hasCurrect: false,
    /**轮播 */
    images: [
      // { baseUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', imgUrl: '' },
      // { baseUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', imgUrl: '' },
      // { baseUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg', imgUrl: '' }
    ]
  }) as IImageHooksState;

  /**获取批改图像状态 */
  const getCorrectImageStatus = (list: Array<CurrentSubject>) => {
    const ims = state.imageManages.filter((im) => im.im.layers.length === 0);
    const noCurrImgs = state.images.filter((v) => v.imgUrl !== '');
    let imsText = '';
    let status = true;
    ims.forEach((v) => {
      const l = list.filter((node) => node.id == v.id);
      if (l.length > 0) {
        imsText += `第${getCHNumber(l[0].id)}题，第${getCHNumber(v.idx)}图 \n`;
        status = false;
      }
    });

    if (ims.length > 0 && noCurrImgs.length === 0) {
      return { text: '图像未批改:\n' + imsText, status };
    } else if (noCurrImgs.length == state.images.length) {
      status = true;
      return { text: '', status };
    }
    return { text: '', status };
  };
  /** 设置获取图像顺序*/
  const changeActiveImageManages = (idx: number, id: AnswersID) => {
    const ilist = state.imageManages.filter((n) => n.id === id).filter((m) => m.idx === idx);
    if (ilist.length > 0) {
      state.activeImageManages = ilist[0];
      state.currentImageIndex = ilist[0].idx;
    }
  };
  /**获取图像当前题目序号 */
  const getActiveImageManagesById = (id: AnswersID) => {
    const ilist = state.imageManages.filter((n) => n.id === id);
    if (ilist.length > 0) {
      state.activeImageManages = ilist[0];
      state.currentImageIndex = ilist[0].idx;
    }
  };
  /**激活当前题的图片 */
  const activateSubjectManages = () => {
    const obj = state.imageDomContain as ImageDomContain;
    /**清空 */
    store.state.imageManages = [];
    Object.keys(obj).forEach((key, idx) => {
      store.addImageTool(obj[key].r as HTMLDivElement, toRaw(obj[key].node), parseInt(key), obj[key].id);
    });
    /**默认激活idx */
    if (store.state.imageManages.length > 0) {
      store.state.activeImageManages = store.state.imageManages[state.currentImageIndex - 1];
    }
  };
  /**初始化图像 */
  const addImageTool = async (dom: HTMLDivElement, node: ImageInfo, idx: number, id: AnswersID) => {
    const imageManage = new ImageToolManage(
      {
        ...node
      },
      dom
    );
    state.imageManages.push({ idx: idx, im: imageManage, id: id });
  };
  /** 获得图片信息并初始化*/
  const initImageUrl = async (submitType: ESubmitType, currentStdHomeWork: StdHomeWork) => {
    if (currentStdHomeWork) {
      /**第一次批改 */
      const img_urls: Array<SimplifyUrls> = [];
      if (submitType === ESubmitType.frist) {
        // store.initImageUrl(currentStdHomeWork.commit.details)
        currentStdHomeWork.commit.details.forEach((n) => {
          n.img_urls.split(',').forEach((v) => {
            img_urls.push({ id: n.id, img_url: v });
          });
        });
      }
      /**订正初始化 */
      if (submitType === ESubmitType.wrong) {
        if (currentStdHomeWork.correct) {
          currentStdHomeWork.commit.details.forEach((n) => {
            /**过滤 */
            if (currentStdHomeWork.wrong_test_ids.filter((r) => r.id === n.id).length > 0) {
              n.img_urls.split(',').forEach((v) => {
                img_urls.push({ id: n.id, img_url: v });
              });
            }
          });
        }
      }

      img_urls.forEach((val) => state.images.push({ baseUrl: val.img_url, id: val.id, imgUrl: '' }));
    }
  };

  const store: IUseImageStore = {
    state,
    addImageTool,
    activateSubjectManages,
    getCorrectImageStatus,
    changeActiveImageManages,
    getActiveImageManagesById,
    initImageUrl
  };

  provide(useImageSymbol, store);

  console.log('完成图像编辑初始化');
  return store;
};

/**
 *  * useImageStore 用户hooks.
 * @function
 * @returns store extend IUseImageStore
 */
export const useImageStore: IUseImageStoreFn = () => {
  const store: IUseImageStore = inject(useImageSymbol) as IUseImageStore;
  return store;
};
